package logic

import (
	"context"
	"user-login/moder/mysql"

	"user-login/userrpc/internal/svc"
	"user-login/userrpc/userrpc"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type PerfectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPerfectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PerfectLogic {
	return &PerfectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PerfectLogic) Perfect(in *userrpc.PerfectRequest) (*userrpc.PerfectResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	err := findUser.FindUserById(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("当前用户不存在")
	}

	if in.Username == findUser.Username {
		return nil, errors.New("号码一致请更该")
	}
	err = findUser.FindUserByWechCode(mysql.DB, in.Username)
	if err != nil {
		return nil, err
	}

	if findUser.ID != 0 {
		return nil, errors.New("当前账号已被注册请更改")
	}
	user := mysql.User{
		Model:    gorm.Model{ID: uint(in.UserId)},
		Username: in.Username,
		Password: in.Password,
	}
	err = user.UserUpdate(mysql.DB)
	if err != nil {
		return nil, err
	}
	return &userrpc.PerfectResponse{}, nil
}
